package queuedemo;

//循环队列
public class MyCircularQueue {

    private int[] elem;
    private int front;
    private int rear;

    //构造器
    public MyCircularQueue(int k) {
        elem = new int[k+1];
    }

    //插入元素，插入成功返回true
    public boolean enQueue(int value) {
        //循环队列满了则插入失败！
        if (isFull()) {
            return false;
        }
        //队尾插入
        elem[rear] = value;
        rear = (rear + 1) % elem.length;
        return true;
    }

    //删除元素，删除成功返回true
    public boolean deQueue() {
        //队列为空删除失败！
        if (isEmpty()) {
            return false;
        }
        //队头删除
        front = (front + 1) % elem.length;
        return true;
    }

    //从队首获取元素
    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        return elem[front];
    }

    //从队尾获取元素
    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        int index = rear == 0 ? elem.length - 1 : rear - 1;
        return elem[index];
    }

    //如果front和rear指向同一块空间则为空
    public boolean isEmpty() {
        return front == rear;
    }


    //如果下一个位置时front，则循环队列满，否则不满
    public boolean isFull() {
        if ((rear + 1) % elem.length == front) {
            return true;
        }
        return false;
    }
}
